package com.yvan.serverless.mybatis;


import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;


@Configuration
@AutoConfigureAfter({SqlSessionFactory.class, MybatisPlusProperties.class})
public class MyBatisAfterAutoConfiguration {
    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    @Autowired
    private MybatisPlusProperties mybatisPlusProperties;

    @Autowired
    private ApplicationContext applicationContext;

//    @Bean
//    public MapperRefresh mybatisMapperRefresh() throws IOException, InterruptedException {
//
////        Resource[] resources = Stream.of(Optional.ofNullable(mybatisPlusProperties.getMapperLocations()).orElse(new String[0]))
////                .flatMap(location -> {
////                    try {
////                        return Stream.of(resourceResolver.getResources(location));
////                    } catch (IOException e) {
////                        throw new RuntimeException(e);
////                    }
////                })
////                .toArray(Resource[]::new);
//        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
//        MapperRefresh mybatisMapperRefresh = new MapperRefresh(mybatisPlusProperties, sqlSessionFactory, 10, 5, true);
//        MapperWatcher mapperWatcher = new MapperWatcher();
//        mapperWatcher.watch();
//        return mybatisMapperRefresh;
//    }

    @Bean
    public DataSourceHelper dataSourceHelper() {
        return new DataSourceHelper();
    }

    @Bean
    public MapperWatcher mapperWatcher() throws IOException, InterruptedException {
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
        MapperWatcher mapperWatcher = new MapperWatcher(sqlSessionFactory, mybatisPlusProperties,true);
        mapperWatcher.watch();
        return mapperWatcher;
    }
}
